require(['jgGrid', 'bootstrap', 'cookie','underscore'], function () {
    var webRoot = G_WEB_ROOT;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    var urls = {
    	queryClassifyByCondition: webRoot + '/sys/queryClassifyByCondition',
    	queryBrandByCondition : webRoot + "/sys/queryBrandByCondition",
    	findClassifyById : webRoot + '/sys/findClassifyById',
    	findBrandById : webRoot + '/sys/findBrandById',
    	deleteBrandByIds : webRoot + '/sys/deleteBrandByIds'
    };

    var selectClassifyId= '';

    var classfiyGridObj = {
    	searchTxt : null,
    	classfiyGridId : "#grid-table",
		cfGridOpt : {
			 url: urls.queryClassifyByCondition,
		        datatype: 'json',
		        mtype: 'POST',
		        autowidth: true,
		        height: 250,
		        colNames: ['id', '类别名', '是否发布', '排序', '创建时间', '操作'],
		        colModel: [
		            {name: 'id', hidedlg: true, hidden: true, width: 60},
		            {name: 'name', sortable: false, editable: true, width: 60, align: 'center'},
		            {name: 'hasPublic',width: 100, sortable: false,editable: true,editoptions: {size: "20", maxlength: "30"},editrules: {required: true},formatter:function(v,o,r){
	                	return r.hasPublic==1?"是":"否";
                    } },
		            {name: 'showIndex',width:120,sortable:false,editable:true,align:'center',editoptions:{size:"20",maxlength:"5"},editrules:{required:true}},
		            {name:'createTime',width:100,sortable:false,align:'center',editable:false,sorttype:"date",editrules:{required:true},formatter:function(v,o,r){
                    	return getSmpFormatDateByLong(r.createTime,false);
                    }},
		            {name:'myac',width:200,fixed:true,sortable:false,align:'center',resize:false,search:false,title:false}
		        ],
		        viewrecords: true,
//		        pager: pager_selector,
		        altRows: true,
		        rowHeight: 36,
		        styleUI: 'Bootstrap',
		        multiselect: true,
		        multiboxonly: true,
		        loadComplete: function (xhr) {
		            var rows = xhr.rows;
		            var ids = $(classfiyGridObj.classfiyGridId).jqGrid('getDataIDs');
		            for (var i = 0; i < ids.length; i++) {
		                var col = ids[i];
		             	if("首页" != rows[i].name){
		             		var html = '<a href="javascript:void(0)" data-index="' + i + '" class="update_classify" style="padding-right:5px;">类别修改</a>' ;
			                $(classfiyGridObj.classfiyGridId).jqGrid('setRowData', col, {myac: html});
		             	}
		            }
		            $('.update_classify').unbind().bind('click', function (e) {
		                var _this = $(this);
		                var idx = _this.attr('data-index');
		                var rowObj = rows[idx];
		                updateClassifyEvent(rowObj, e);
		            });
		            $(classfiyGridObj.classfiyGridId).setGridWidth($(classfiyGridObj.classfiyGridId).parent().width());
		        },
		        onSelectRow:function(id){
		        	selectClassifyId = id;
		        	brandGridObj.initGrid(selectClassifyId, null);
		        	addBrand(selectClassifyId);
		        }
		},
        init: function (_searchTxt) {
            var self = this;
            if (_.isNull(self.searchTxt)) {
                $(self.classfiyGridId).jqGrid(self.cfGridOpt);
            }
            if (_searchTxt != self.searchTxt) {
                self.searchTxt = _searchTxt;
                self.initGrid(_searchTxt);
            }
        },
        initGrid: function (_searchTxt) {
            var self = this;
            $(self.classfiyGridId).clearGridData().
            	setGridParam({postData: {'searchTxt': _searchTxt}}).trigger("reloadGrid");
            self.resizeGrid();
        },
        resizeGrid: function () {
            var self = this;
            var parentDom = $('#gbox_' + self.classfiyGridId.split('#')[1]).parent();
            $(self.classfiyGridId).setGridWidth(parentDom.width());
        }
    };


    var brandGridObj = {
        	searchTxt : null,
        	brandGridId : "#brandGrid",
    		bGridOpt : {
    				url: urls.queryBrandByCondition,
    	            datatype: 'json',
    	            mtype: 'POST',
    	            autowidth: true,
    	            height: 300,
    	            colNames: ['id','classifyId', '类别名', '品牌名', '是否发布', '排序', '创建时间', '操作'],
    	            colModel: [
    	                {name: 'id', hidedlg: true, hidden: true, width: 60},
    	                {name: 'classifyId', hidedlg: true, hidden: true, width: 60},
    	                {name: 'classifyName', sortable: false, editable: true, width: 60, align: 'center'},
    	                {name: 'name', sortable: false, editable: true, width: 60, align: 'center'},
    	                {name: 'hasPublic',width: 100, sortable: false,editable: true,editoptions: {size: "20", maxlength: "30"},editrules: {required: true},formatter:function(v,o,r){
    	                	return r.hasPublic==1?"是":"否";
	                    } },
    	                {name: 'showIndex',width:120,sortable:false,editable:true,align:'center',editoptions:{size:"20",maxlength:"5"},editrules:{required:true}},
    	                {name:'createTime',width:100,sortable:false,align:'center',editable:false,sorttype:"date",editrules:{required:true},formatter:function(v,o,r){
	                    	return getSmpFormatDateByLong(r.createTime,false);
	                    }},
    	                {name:'myac',width:200,fixed:true,sortable:false,align:'center',resize:false,search:false,title:false}
    	            ],
    	            viewrecords: true,
    	            pager: "#brandGridPager",
					// rowNum: 20,	//默认20
    	            altRows: true,
    	            rowHeight: 36,
    	            styleUI: 'Bootstrap',
    	            multiselect: true,
    	            multiboxonly: true,
    	            loadComplete: function (xhr) {
    	                var rows = xhr.rows;
    	                var ids = $(brandGridObj.brandGridId).jqGrid('getDataIDs');
    	                for (var i = 0; i < ids.length; i++) {
    	                    var col = ids[i], html =
    	                    	'<a href="javascript:void(0)" data-index="' + i + '" class="update_brand" style="padding-right:5px;">品牌修改</a>'
    	                        + '<a href="javascript:void(0)" data-index="' + i + '" class="to_brand" >产品管理</a>';
    	                    $(brandGridObj.brandGridId).jqGrid('setRowData', col, {myac: html});
    	                }
    	                $('.update_brand').unbind().bind('click', function (e) {
    	                    var _this = $(this);
    	                    var idx = _this.attr('data-index');
    	                    var rowObj = rows[idx];
    	                    rowObj.classifyId = selectClassifyId;
    	                    updateBrandEvent(rowObj, e);
    	                });
    	                $('.to_brand').unbind().bind('click', function () {
    	                    var _this = $(this);
    	                    var idx = _this.attr('data-index');
    	                    var rowObj = rows[idx];
    	                    $.cookie('selectClassifyId',rowObj.classifyId,{path:'/'});
    	                    window.location.href = webRoot + '/sys/productItemView?brandId=' + rowObj.id;
    	                });
    	                $(brandGridObj.brandGridId).setGridWidth($(brandGridObj.brandGridId).parent().width());
    	            }
    		},
            init: function (_searchTxt) {
                var self = this;
                if (_.isNull(self.searchTxt)) {
                    $(self.brandGridId).jqGrid(self.bGridOpt);
                }
            },
            initGrid: function (_classifyId, _searchTxt) {
                var self = this;
                $(self.brandGridId).clearGridData().
                	setGridParam({postData:
                			{"classifyId": _classifyId, 'searchTxt': _searchTxt},
                			}).trigger("reloadGrid");
                self.resizeGrid();
            },
            resizeGrid: function () {
                var self = this;
                var parentDom = $('#gbox_' + self.brandGridId.split('#')[1]).parent();
                $(self.brandGridId).setGridWidth(parentDom.width());
            }
        };

    // EVENT
    //=====================================================
    $("#searchBtnId").click(function(){
    	var searchTxt = $("#searchNameTxt").val();
    	classfiyGridObj.initGrid(searchTxt);
    });
    $("#searchBtnId2").click(function(){
    	var searchTxt = $("#searchNameTxt2").val();
    	brandGridObj.initGrid(null, searchTxt);
    });

    function addBrand(id){
    	$("#addBtnId2").show();
    	$("#addBtnId2").unbind().bind('click',function(){
    		$("#itemModalLabel2 div").html("类别 >>> 品牌");
    		$("#itemModalLabel2 input").val(id);
        	$('#addModal').modal('show');
//        	brandGridObj.initGrid(null, null);
	    });
    }

	$("#delBtnId2").unbind().bind('click',function(){
		var brandIds = $(brandGridObj.brandGridId).jqGrid('getGridParam','selarrrow');
		if(brandIds.length > 0){
			var ids = "";
            $.post(urls.deleteBrandByIds, {'idsArr':brandIds.join()},function(rs){
            	if(rs.type){
            		alert("删除成功");
            		brandGridObj.initGrid(null, null);
            	}else{
            		alert("删除失败");
            	}
              });
        }else{
            alert("请选择需要删除的记录！");
        }
	});



	//用jquery
	function getTextByJquery() {
	    var str = "";
	    //遍历name为txt的所有input元素
	    $("input[name='txt']").each(function () {
	        str += $(this).val() + ",";
	    });
	    //去掉最后一个逗号(如果不需要去掉，就不用写)
	    if (str.length > 0) {
	        str = str.substr(0,str.length - 1);
	    }
	    return str;
	}

    function updateClassifyEvent(obj, e) {
    	$("#modalClassifyId").val(obj.id);
    	$("#modalBrandId").val(null);
    	$("#modalName").val(obj.name);
    	$("#modalShowIndex").val(obj.showIndex);
    	$("#modalShowIndex").attr("readonly", true);
     	if(obj.hasPublic == 1 ){
    		$("#modalhP1").attr("checked",true);
    	}else{
    		$("#modalhP2").attr("checked",true);
    	}
    	$("#itemModalLabel div").html("类别 ");
    	$('#updateModal').modal('show');
    }
    function updateBrandEvent(obj, e) {
    	$("#modalClassifyId").val(null);
    	$("#modalBrandId").val(obj.id);
    	$("#modalName").val(obj.name);
    	$("#modalShowIndex").val(obj.showIndex);
    	$("#modalShowIndex").attr("readonly", false);
     	if(obj.hasPublic == 1 ){
    		$("#modalhP1").attr("checked",true);
    	}else{
    		$("#modalhP2").attr("checked",true);
    	}
    	$("#itemModalLabel div").html("品牌  > " + obj.classifyName);
    	$('#updateModal').modal('show');
    }
    //=====================================================

    $(function(){
    	classfiyGridObj.init();
    	brandGridObj.init();
    });


    //扩展Date的format方法
    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }
    /**
    *转换日期对象为日期字符串
    * @param date 日期对象
    * @param isFull 是否为完整的日期数据,
    *               为true时, 格式如"2000-03-05 01:05:04"
    *               为false时, 格式如 "2000-03-05"
    * @return 符合要求的日期字符串
    */
    function getSmpFormatDate(date, isFull) {
        var pattern = "";
        if (isFull == true || isFull == undefined) {
            pattern = "yyyy-MM-dd hh:mm:ss";
        } else {
            pattern = "yyyy-MM-dd";
        }
        return getFormatDate(date, pattern);
    }
    /**
    *转换当前日期对象为日期字符串
    * @param date 日期对象
    * @param isFull 是否为完整的日期数据,
    *               为true时, 格式如"2000-03-05 01:05:04"
    *               为false时, 格式如 "2000-03-05"
    * @return 符合要求的日期字符串
    */

    function getSmpFormatNowDate(isFull) {
        return getSmpFormatDate(new Date(), isFull);
    }
    /**
    *转换long值为日期字符串
    * @param l long值
    * @param isFull 是否为完整的日期数据,
    *               为true时, 格式如"2000-03-05 01:05:04"
    *               为false时, 格式如 "2000-03-05"
    * @return 符合要求的日期字符串
    */

    function getSmpFormatDateByLong(l, isFull) {
        return getSmpFormatDate(new Date(l), isFull);
    }
    /**
    *转换long值为日期字符串
    * @param l long值
    * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss
    * @return 符合要求的日期字符串
    */

    function getFormatDateByLong(l, pattern) {
        return getFormatDate(new Date(l), pattern);
    }
    /**
    *转换日期对象为日期字符串
    * @param l long值
    * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss
    * @return 符合要求的日期字符串
    */
    function getFormatDate(date, pattern) {
        if (date == undefined) {
            date = new Date();
        }
        if (pattern == undefined) {
            pattern = "yyyy-MM-dd hh:mm:ss";
        }
        return date.format(pattern);
    }


});
